
import { _decorator, Component, Node, instantiate, sp, Vec3, Vec2, tween, SpriteFrame, dragonBones, resources } from 'cc';
import { AppLauncher } from './AppLauncher';
import { UIBattleEndController } from './UIBattleEndController';
import { UICountdownController } from './UICountdownController';
// import { UICountdownController } from './UICountdownController';
const { ccclass, property } = _decorator;

// 角色数据
var CharacterDataListLeft = [
    { skeletonIndex: 0, x: -430, y: -40, speed: 25, atk: 70, def: 30, long: false, blood: 100 },
    { skeletonIndex: 1, x: -430, y: -230, speed: 13, atk: 60, def: 30, long: false, blood: 100 },
]

var CharacterDataListRight = [
    { skeletonIndex: 2, x: -430, y: -40, speed: 11, atk: 60, def: 30, long: false, blood: 100 },
    { skeletonIndex: 3, x: -430, y: -230, speed: 15, atk: 60, def: 30, long: false, blood: 100 },
]

// 角色状态
var Character_STATE_WAIT = 1  // 待机
var Character_STATE_MOVE = 2  // 攻击
var Character_STATE_BACK = 3
var Character_STATE_ATK = 4
var Character_STATE_DEF = 5
var Character_STATE_DIE = 6

@ccclass('UIBattleFieldController')
export class UIBattleFieldController extends Component {

    // 执行攻击角色的index
    private orderIndex: number = 0;
    // 被攻击角色的index
    private targetIndex: number = 0;
    // 待攻击的角色数组
    private orderArray: any[] = null;
    // 我方角色的数组
    private leftCharacters: any[] = null;
    // 敌方角色的数组
    private rightCharacters: any[] = null;

    start() {
        this._startGame();
    }

    private _startGame() {
        // 初始化角色数据
        this._initRoleData();
        // 初始化角色动画
        this._initRoleAnimate();
        // 开始角色攻击逻辑
        var uiCountDown = instantiate(AppLauncher.Instance.UICountdown);
        AppLauncher.Instance.Canvas.addChild(uiCountDown);
        var compUICountDown = uiCountDown.getComponent(UICountdownController);
        compUICountDown.setCountDown(3, () => {
            uiCountDown.removeFromParent();

            //开始游戏
            this.orderIndex = 0
            this._nextAttack()
        });
    }

    // 初始化战斗数据
    private _initRoleData() {
        this.orderArray = []
        for (var i = 0; i < 2; i++) {
            this.orderArray[i] = { "speed": CharacterDataListLeft[i].speed, "atk": CharacterDataListLeft[i].atk, "def": CharacterDataListLeft[i].def, "id": i, "camp": 0, "state": Character_STATE_WAIT, "blood": CharacterDataListLeft[i].blood }
            this.orderArray[i + 2] = { "speed": CharacterDataListRight[i].speed, "atk": CharacterDataListRight[i].atk, "def": CharacterDataListRight[i].def, "id": i, "camp": 1, "state": Character_STATE_WAIT, "blood": CharacterDataListRight[i].blood }
        }
        //根据出手速度排序
        function numberorder(a: any, b: any) { return b.speed - a.speed }   // 降序排序
        this.orderArray.sort(numberorder)

        this.orderIndex = 0
    }

    // 初始化动画
    private _initRoleAnimate() {
        if (this.leftCharacters) {
            for (var i = 0; i < this.leftCharacters.length; i++) {
                if (this.leftCharacters[i]) {
                    this.leftCharacters[i].removeFromParent();
                }
            }
        }
        if (this.rightCharacters) {
            for (var i = 0; i < this.rightCharacters.length; i++) {
                if (this.rightCharacters[i]) {
                    this.rightCharacters[i].removeFromParent();
                }
            }
        }

        this.leftCharacters = []
        this.rightCharacters = []
        for (var i = 0; i < 2; i++) {
            //初始化左边阵容动画
            var data = CharacterDataListLeft[i]
            this.leftCharacters[i] = instantiate(AppLauncher.Instance.PrefabCharacter)
            this.leftCharacters[i].setPosition(data.x, data.y)
            AppLauncher.Instance.Canvas.addChild(this.leftCharacters[i])

            this.leftCharacters[i].getComponent(dragonBones.ArmatureDisplay).dragonAsset = AppLauncher.Instance.DragonBonesAsset[data.skeletonIndex];
            this.leftCharacters[i].getComponent(dragonBones.ArmatureDisplay).dragonAtlasAsset = AppLauncher.Instance.DragonBonesAtlAsset[data.skeletonIndex];

            this.leftCharacters[i].getComponent(dragonBones.ArmatureDisplay).armatureName = "待机";
            this.leftCharacters[i].getComponent(dragonBones.ArmatureDisplay).playAnimation("待机", -1);

            //初始化右边阵容动画
            data = CharacterDataListRight[i]
            this.rightCharacters[i] = instantiate(AppLauncher.Instance.PrefabCharacter)
            this.rightCharacters[i].setPosition(-data.x, data.y)
            AppLauncher.Instance.Canvas.addChild(this.rightCharacters[i])
            var originScale = this.rightCharacters[i].scale
            this.rightCharacters[i].setScale(new Vec3(-originScale.x, originScale.y, originScale.z))

            this.rightCharacters[i].getComponent(dragonBones.ArmatureDisplay).dragonAsset = AppLauncher.Instance.DragonBonesAsset[data.skeletonIndex];
            this.rightCharacters[i].getComponent(dragonBones.ArmatureDisplay).dragonAtlasAsset = AppLauncher.Instance.DragonBonesAtlAsset[data.skeletonIndex];

            this.rightCharacters[i].getComponent(dragonBones.ArmatureDisplay).armatureName = "待机";
            this.rightCharacters[i].getComponent(dragonBones.ArmatureDisplay).playAnimation("待机", -1);
            this.rightCharacters[i].getComponent("CharacterController").setBloodSpriteFrame(SpriteFrame.createWithImage(AppLauncher.Instance.ImageAssetHealthPercent));
        }
    }

    // 设置状态
    private _setAnimState(obj: any, state: number) {
        obj.state = state
        if (state == Character_STATE_MOVE) {
            var targetCamp = 1
            if (obj.camp == 1) {
                targetCamp = 0
            }
            var target = null
            //确定攻击对象
            for (var i = 0; i < 4; i++) {
                if (this.orderArray[i].camp == targetCamp && this.orderArray[i].state != Character_STATE_DIE) {
                    this.targetIndex = i
                    target = this.orderArray[i]
                    break
                }
            }
            if (target == null) {
                //一方全部死亡，游戏结束
                var str = "恭喜，您胜利啦！"
                var color = "#1FFA16";
                if (obj.camp == 1) {
                    str = "失败，再接再厉！"
                    color = "#FFFFFF";
                }

                var uiBattleEnd = instantiate(AppLauncher.Instance.UIBattleEnd);
                AppLauncher.Instance.Canvas.addChild(uiBattleEnd);
                var compUIBattleEnd = uiBattleEnd.getComponent(UIBattleEndController);
                compUIBattleEnd.setTitle(str, color);
                compUIBattleEnd.setBtnOnclicked((opt: number) => {
                    if (opt == 1) {
                        // 再玩一局
                        this._startGame();
                    }
                })

                return
            }
            //移动到目标位置
            var targetPos = new Vec2(0, 0)
            //是否远程
            var isLong = null
            var animHandle = null

            if (obj.camp == 1) {
                // 阵营1在右边
                isLong = CharacterDataListRight[obj.id].long

                animHandle = this.rightCharacters[obj.id]
            } else {
                // 阵营0在左边
                isLong = CharacterDataListLeft[obj.id].long

                animHandle = this.leftCharacters[obj.id]
            }
            if (isLong) {
                this._setAnimState(obj, Character_STATE_ATK)
                return
            }

            if (targetCamp == 1) {
                targetPos.x = -(CharacterDataListRight[target.id].x + 80)
                targetPos.y = CharacterDataListRight[target.id].y
            } else {
                targetPos.x = (CharacterDataListRight[target.id].x + 80)
                targetPos.y = CharacterDataListRight[target.id].y
            }

            animHandle.setSiblingIndex(animHandle.parent.children.length - 1)

            var callback = function () {
                //进入到攻击状态
                this._setAnimState(obj, Character_STATE_ATK)
            }.bind(this)
            tween(animHandle).to(0.5, { position: new Vec3(targetPos.x, targetPos.y, 0) }).call(callback).start();
        } else if (state == Character_STATE_ATK) {
            var animHandle = this.leftCharacters[obj.id]
            if (obj.camp == 1) {
                animHandle = this.rightCharacters[obj.id]
            }

            if (obj.camp == 1) {
                animHandle.getComponent(dragonBones.ArmatureDisplay).armatureName = "技能1";
                animHandle.getComponent(dragonBones.ArmatureDisplay).playAnimation("技能1", -1);
                let player3 = animHandle.getChildByName("player3");
                player3.active = true
                //初始化角色技能动画
                if(this.orderArray[obj.id].id+2==2){
                    player3.setPosition(0,-45);
                }else{
                    player3.setPosition(117.7,0);
                }
                player3.getComponent(dragonBones.ArmatureDisplay).dragonAsset = AppLauncher.Instance.DragonBonesAsset[this.orderArray[obj.id].id+2];
                player3.getComponent(dragonBones.ArmatureDisplay).dragonAtlasAsset = AppLauncher.Instance.DragonBonesAtlAsset[this.orderArray[obj.id].id+2];
                player3.getComponent(dragonBones.ArmatureDisplay).armatureName = "技能1特效1";
                player3.getComponent(dragonBones.ArmatureDisplay).playAnimation("技能1特效1", -1);
            }else{
                animHandle.getComponent(dragonBones.ArmatureDisplay).armatureName = "技能1";
                animHandle.getComponent(dragonBones.ArmatureDisplay).playAnimation("技能1", -1);
                let player3 = animHandle.getChildByName("player3");
                player3.active = true
                 //初始化角色技能动画
                 if(this.orderArray[obj.id].id==0){
                    player3.setPosition(0,45);
                }else{
                    player3.setPosition(0,0)
                }
                //初始化角色技能动画
                player3.getComponent(dragonBones.ArmatureDisplay).dragonAsset = AppLauncher.Instance.DragonBonesAsset[this.orderArray[obj.id].id];
                player3.getComponent(dragonBones.ArmatureDisplay).dragonAtlasAsset = AppLauncher.Instance.DragonBonesAtlAsset[this.orderArray[obj.id].id];
                player3.getComponent(dragonBones.ArmatureDisplay).armatureName = "技能1特效1";
                player3.getComponent(dragonBones.ArmatureDisplay).playAnimation("技能1特效1", -1);
            }
            //计算减小的血量
            var tagetDef = null
            var objAtk = null
            var tagetNode = null
            var originPos = new Vec2(0, 0)

            if (obj.camp == 0) {
                tagetDef = CharacterDataListRight[this.orderArray[this.targetIndex].id].def
                objAtk = CharacterDataListLeft[obj.id].atk
                tagetNode = this.rightCharacters[this.orderArray[this.targetIndex].id]

                originPos.x = CharacterDataListLeft[obj.id].x
                originPos.y = CharacterDataListLeft[obj.id].y
            } else {
                tagetDef = CharacterDataListLeft[this.orderArray[this.targetIndex].id].def
                objAtk = CharacterDataListRight[obj.id].atk
                tagetNode = this.leftCharacters[this.orderArray[this.targetIndex].id]

                originPos.x = -CharacterDataListRight[obj.id].x
                originPos.y = CharacterDataListRight[obj.id].y
            }

            var xaiw = function () {
                let player3 = animHandle.getChildByName("player3");
                player3.active = false;
                player3 = null;
                this.orderArray[this.targetIndex].blood = this.orderArray[this.targetIndex].blood + tagetDef - objAtk
                if (this.orderArray[this.targetIndex].blood <= 0) {
                    this.orderArray[this.targetIndex].blood = 0
                }

                //掉血
                tagetNode.getComponent("CharacterController").setBlood(this.orderArray[this.targetIndex].blood / 100)
                if (this.orderArray[this.targetIndex].blood <= 0) {
                    //角色死亡
                    this._setAnimState(this.orderArray[this.targetIndex], Character_STATE_DIE)
                }
            }.bind(this);

            tween(animHandle).to(0.7, {}).call(xaiw).start();
            var callback = function () {
                //进入到待机状态
                this._setAnimState(obj, Character_STATE_WAIT)
            }.bind(this)
            setTimeout(function () {
                tween(animHandle).to(0.5, { position: new Vec3(originPos.x, originPos.y, 0) }).call(callback).start();
            }, 700);

        } else if (state == Character_STATE_DIE) {
            var animNode = this.leftCharacters[obj.id]
            if (obj.camp == 1) {
                animNode = this.rightCharacters[obj.id]
            }

            animNode.getComponent("CharacterController").setBloodVisible(false)
            animNode.getComponent(dragonBones.ArmatureDisplay).armatureName = "死亡";
            animNode.getComponent(dragonBones.ArmatureDisplay).playAnimation("死亡", -1);
            animNode.getComponent(dragonBones.ArmatureDisplay).addEventListener(dragonBones.EventObject.COMPLETE, () => {
                animNode.active = false
                animNode = null;
            }, this)

        } else if (state == Character_STATE_WAIT) {
            //回到原始状态
            var animHandle = this.leftCharacters[obj.id]
            if (obj.camp == 1) {
                animHandle = this.rightCharacters[obj.id]
            }
            animHandle.getComponent(dragonBones.ArmatureDisplay).armatureName = "待机"
            animHandle.getComponent(dragonBones.ArmatureDisplay).playAnimation("待机", 1);
            this.orderIndex = this.orderIndex + 1
            this._nextAttack()
        }
    }

    // 开始攻击
    private _nextAttack() {
        if (this.orderIndex > 3) {
            this.orderIndex = 0
        }
        var attacker = this.orderArray[this.orderIndex]
        if (attacker.state == Character_STATE_WAIT) {
            this._setAnimState(attacker, Character_STATE_MOVE)
        } else {
            this.orderIndex = this.orderIndex + 1
            this._nextAttack()
        }
    }

}